package com.baomidou.springwind.controller;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.framework.controller.SuperController;
import com.baomidou.kisso.SSOConfig;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.SSOToken;
import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.kisso.annotation.Permission;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.springwind.common.HoorayosHelper;
import com.baomidou.springwind.common.HttpHelper;
import com.baomidou.springwind.common.SHA1Helper;
import com.baomidou.springwind.entity.Member;
import com.baomidou.springwind.service.IMemberService;

/**
 * <p>
 * 账户相关操作
 * </p>
 * 
 * @author Koumiba
 * @Date 2017-03-27
 */
@Controller
@RequestMapping("/account")
public class AccountController extends SuperController {
	@Autowired
	private IMemberService memberService;
	
	/**
	 * ajax 入口
	 * 
	 * @param model
	 */
	@ResponseBody
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/ajax")
	public String ajax(String ac) {
		if (ac.equals("login"))
			return login();
		if (ac.equals("register"))
			return register();
		if (ac.equals("checkUsername"))
			return checkUsername();
		if (ac.equals("logout"))
			return logout();
		return "";
	}
	/**
	 * 个人中心
	 * @return String
	 * koumiba
	 * 2017年3月30日
	 */
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/index")
	public String index(Model model){
		model.addAttribute("errorCode", HoorayosHelper.getErrorCodeMap());
		//验证是否登入
		if(!HoorayosHelper.checkLogin(request)){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noLogin"));
			return "error";
		}

		EntityWrapper ew = new EntityWrapper<Member>();
		ew.where("tbid="+HoorayosHelper.getMemberId(request));
		Member member = new Member().selectOne(ew);

		String global_title = "index";
		model.addAttribute("member", member);
		model.addAttribute("global_title", "index");
		return "/sysapp/account/index";
	}
	
	
	/*************************
	 *    私有方法 
	 *************************/
	private String checkUsername() {
		EntityWrapper ew = new EntityWrapper(new Member());
		ew.and("username='"+request.getParameter("param")+"'");
		Map<String, String> cb = new HashMap<String,String>();
		if(new Member().selectCount(ew)<1){
			cb.put("info", "");
			cb.put("status", "y");
		}else{
			cb.put("info", "用户名已存在，请更换");
			cb.put("status", "n");
		}
		
		return JSONObject.toJSONString(cb);
	}

	/**
	 * 登录
	 */
	private String login() {
		String temp = request.getParameter("rememberMe");
		int rememberMe = temp==null ? 0 : 1;
		EntityWrapper ew = new EntityWrapper(new Member());
		ew.setSqlSelect("tbid,username,password,lastlogindt,thislogindt,lastloginip,thisloginip");
		ew.where("username='"+request.getParameter("username")+"' AND password='"+SHA1Helper.SHA1((request.getParameter("password")))+"'");
		Member user = new Member().selectOne(ew);
		Map<String, String> cb = new HashMap<String,String>();
		
		if(user!=null && user.getTbid()>0){
			user.setLastlogindt(user.getLastlogindt());
			user.setLastloginip(user.getLastloginip());
			user.setThislogindt(new Date());
			user.setThisloginip(HttpHelper.getIpAddr(request));
			memberService.insertOrUpdate(user);
			
			SSOToken st = new SSOToken(request);
			st.setId(user.getTbid());
			st.setData(user.getUsername());
			
			// 记住密码，设置 cookie 时长 1 周 = 604800 秒
			
			if (rememberMe == 1) {
				request.setAttribute(SSOConfig.SSO_COOKIE_MAXAGE, 604800);
			}
			
			SSOHelper.setSSOCookie(request, response, st, true);
			response.addCookie(HttpHelper.generCookie("memberID", user.getTbid().toString(), 24*7*60));
			
			cb.put("info", "");
			cb.put("status", "y");
			
			//处理登录用户信息到cookie
			Map<String, Object> userinfo = new HashMap<String, Object>();
			userinfo.put("username", request.getParameter("username"));
			userinfo.put("password", request.getParameter("password")); //明文 TODO待优化
			userinfo.put("rememberMe", rememberMe);
			userinfo.put("avatar", rememberMe);
//			$userinfo['password'] = $_POST['rememberMe'] ? authcode($_POST['password'], 'ENCODE') : '';
			userinfo.put("avatar", HoorayosHelper.getAvatar(request, user.getTbid().intValue(), "l"));
			response.addCookie(HttpHelper.generCookie("userinfo", JSONObject.toJSONString(userinfo),24*7*60));
		}else{
			cb.put("info", "");
			cb.put("status", "n");
		}
		return JSONObject.toJSONString(cb);
	}

	/**
	 * 注册
	 */
	private String register() {
		String regUsername = request.getParameter("reg_username");
		EntityWrapper ew = new EntityWrapper(new Member());
		ew.and("username", regUsername);
		Map<String, String> cb = new HashMap<String,String>();
		if(new Member().selectCount(ew) > 0){
			cb.put("info", "");
			cb.put("status", "n");
		}else{
			ew = new EntityWrapper(new Member());
			ew.orderBy("tbid", false);
			Member temp = new Member().selectOne(ew);
			int lastTbid = temp.getTbid().intValue() + 1;
			Member newMember = new Member();
			newMember.setTbid((long)lastTbid);
			newMember.setUsername(request.getParameter("reg_username"));
			newMember.setPassword(SHA1Helper.SHA1(request.getParameter("reg_password")));
			newMember.setLockpassword(request.getParameter("reg_password"));
			newMember.setThislogindt(new Date());
			newMember.setRegdt(new Date());
			newMember.setThisloginip(HttpHelper.getIpAddr(request));
			cb.put("info", regUsername);
			cb.put("status", "y");
			memberService.insertOrUpdate(newMember);
		}
			
		return JSONObject.toJSONString(cb);
	}

	/**
	 * 退出
	 */
	private String logout() {
		SSOHelper.clearLogin(request, response);
		response.addCookie(HttpHelper.generCookie("memberID", "", 24*7*60));
		//手动退出，取消userinfo cookie里的自动登录选项
		Map<String, Object> userinfo = new HashMap<String, Object>();
		userinfo.put("password", ""); 
		userinfo.put("rememberMe", 0);

		response.addCookie(HttpHelper.generCookie("userinfo", JSONObject.toJSONString(userinfo),24*7*60));
		return redirectTo("/index/home");
	}
	
	

}
